import { Message } from 'element-ui'

// 内核
import cloudbase from '@cloudbase/js-sdk/app'
// 登录模块
import '@cloudbase/js-sdk/auth'
// 云函数模块
import '@cloudbase/js-sdk/functions'
// 云存储模块
import '@cloudbase/js-sdk/storage'
// 数据库模块
// import '@cloudbase/js-sdk/database'
// 实时推送模块，引入前必须首先引入数据库模块
// import '@cloudbase/js-sdk/realtime'
// 广告上报模块
// import '@cloudbase/js-sdk/analytics'

const app = cloudbase.init({
  env: 'igelato-0gk3btjj255216f4'
})

const auth = app.auth({
  persistence: 'local'
})
auth.signInAnonymously()

let store
async function request(func_name, val = {}) {
  if (!store) {
    const res = await import('@/store/index')
    // eslint-disable-next-line require-atomic-updates
    store = res.default
  }

  // 添加token
  val.token = store.getters.token

  // 发送请求
  const { result: { errcode, msg, data, token }} = await app
    .callFunction({
      name: func_name,
      data: val
    })

  // 一切正常
  if (errcode === 0) {
    if (token) {
      store.commit('user/SET_TOKEN', token)
    }
    return data
  }

  if (errcode === 401) {
    store.dispatch('user/logout')
  } else {
    Message.error(msg || '异常！！！')
  }
  return Promise.reject()
}

export default request

